package com.aaa.data;

import com.aaa.config.SSLHelper;
import com.aaa.entity.Book;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 杨森
 * @version 1.0
 * @Title: data source
 * @date 2020/8/4 14:49
 */
public class BookList extends com.aaa.util.DataProcessing {
    private static ExecutorService executorService;


    private static String dataSource;

    public static List<Book> setDataSource(String dataSource,String key,ExecutorService executorService){
        BookList.dataSource =dataSource;
        BookList.executorService =executorService;
        SSLHelper.init();
        if("biquge5200".equals(dataSource)){
            try {
                return biquge5200(key);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if("biquge".equals(dataSource)){
            try {
                return biquge(key);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    private static List<Book> biquge5200(String key) throws InterruptedException {
        Map<Integer,List<Book>> bookDtoMaps = new HashMap<>(3);
        Pattern pattern = Pattern.compile("<a\\s*href=\"?([\\w\\W]*?)\"?[\\s]*?[^>]>([\\s\\S]*?)(?=</a>)");
        Document document = null;
        try {
            document = Jsoup.connect("https://www.biquge5200.com/modules/article/search.php?searchkey=" + key).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Node> tbody = document.select("tbody").get(0).childNodes();
        Map<Integer, List<Node>> integerListMap = splitList(tbody, 3);
        CountDownLatch latch=new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            final int ins=i;
            executorService.execute(() -> {
                bookDtoMaps.put(ins,get1(integerListMap.get(ins), pattern));
                latch.countDown();
            });
        }
        latch.await();
        List<Book> bookDtos=new ArrayList<>(tbody.size());
        for (int i = 0; i < 3; i++) {
            bookDtos.addAll(bookDtoMaps.get(i));
        }
        executorService.shutdown();
        return bookDtos;
    }
    public static List<Book> get1(List<Node> tbody,Pattern pattern){
        List<Book> bookDtos = new ArrayList<>(tbody.size());
        tbody.forEach(tr -> {
            if("".equals(tr.toString().trim())){
                return;
            }
            String s1 = tr.childNode(1).toString();
            if (s1.matches("(.*)文章名称(.*)")) {
                return;
            }

            Book book = new Book();
            String href = "";
            Node node = tr.childNode(1).childNode(0);
            String reg = ".*</a>.*";
            String s = node.toString();
            if (s.matches(reg)) {
                Matcher matcher = pattern.matcher(s);
                if (matcher.find()) {
                    href = matcher.group(1);
                    String nameCode1 = href.substring(0, href.length() - 1);
                    String nameCode = nameCode1.substring(nameCode1.lastIndexOf("/") + 1, nameCode1.length());
                    book.setBookCode(nameCode);
                }
            }

            book.setBookName(node.childNode(0).toString());
            book.setBookAuthor(tr.childNode(5).childNode(0).toString());
            book.setBookData(dataSource);
            bookDtos.add(book);
        });
        return bookDtos;
    }
    private static List<Book> biquge(String key) throws InterruptedException {
        Map<Integer,List<Book>> bookDtoMaps = new HashMap<>(3);
        Pattern pattern = Pattern.compile("<a\\s*href=\"?([\\w\\W]*?)\"?[\\s]*?[^>]>([\\s\\S]*?)(?=</a>)");
        Document document = null;
        try {
            document = Jsoup.connect("https://www.biquge.com/searchbook.php?keyword=" + key).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Elements item = document.getElementsByClass("item");
        Map<Integer, List<Element>> integerListMap = splitList(item, 3);
        CountDownLatch latch=new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            final int ins=i;
            executorService.execute(() -> {
                bookDtoMaps.put(ins,get(integerListMap.get(ins), pattern));
                latch.countDown();
            });
        }
        latch.await();
        List<Book> bookDtos=new ArrayList<>(item.size());
        for (int i = 0; i < 3; i++) {
            bookDtos.addAll(bookDtoMaps.get(i));
        }
        executorService.shutdown();

        return bookDtos;
    }

    public static List<Book> get(List<Element> item,Pattern pattern){
        List<Book> bookDtos = new ArrayList<>(item.size());
        item.forEach(element -> {
            String reg = ".*</a>.*";
            Book book = new Book();
            String img = element.select("img").toString();
            String newImg=img.substring(0,10)+"https://www.biquge.com"+img.substring(10,img.length());
            book.setBookImage(newImg);
            Elements dt = element.select("dt");
            Elements dd = element.select("dd");
            book.setBookIntro(dd.get(0).childNode(0).toString());
            Node node = dt.get(0).childNode(1);
            Node node1 = dt.get(0).childNode(0).childNode(0);
            book.setBookAuthor(node1.toString());
            Matcher matcher = pattern.matcher(node.toString());
            if (matcher.find()) {
                book.setBookCode(matcher.group(1).replace("/",""));
            }
            book.setBookName(node.childNode(0).toString());
            book.setBookData(dataSource);
            bookDtos.add(book);
        });
        return bookDtos;
    }

}
